package cn.kvchoi.proactor_aio.server;

import cn.kvchoi.proactor_aio.server.handlers.AcceptCompletionHandler;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 主动器初始化
 */
public class ProactorInitiator {

    public void initiateProactiveServer(int port) throws IOException {
        // 创建一个线程池，并指定为异步channel处理io操作
        ExecutorService executor = Executors.newFixedThreadPool(10, Executors.defaultThreadFactory());
        AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(executor);

        // Base on jdk 7's AIO socket model (the NewIO 2.0)
        AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open(channelGroup).bind(new InetSocketAddress(port));
        SessionStateAttachment attachment = new SessionStateAttachment();
        AcceptCompletionHandler acceptCompletionHandler = new AcceptCompletionHandler(listener);
        listener.accept(attachment, acceptCompletionHandler);
        System.out.println("Proactor Initiator Running on " + Thread.currentThread().getName());
    }
}